package vn.mahjonggame.game.request;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import vn.mahjonggame.game.Mahjong;
import vn.mahjonggame.game.MahjongExtension;
import vn.mahjonggame.metadata.GameActionType;
import vn.mahjonggame.metadata.MObject;
import vn.mahjonggame.metadata.Player;
import vn.mahjonggame.metadata.Response;
import vn.mahjonggame.metadata.UserVarName;

import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;

public class UpdateRoomHandler extends BaseClientRequestHandler {

	@Override
	public void handleClientRequest(User user, ISFSObject params) {
		//TODO
	}
	
	public void updateRoom(final MahjongExtension ext, final User user, boolean isJoin){
		setParentExtension(ext);
		Mahjong mahjong = ext.getMahjong();
		Room room = ext.getGameRoom();
		
		if(!isJoin){
			room.removeUser(user);
		}
		
		List<User> users = room.getUserList();
		
		for(int i = 0; i < users.size(); i++){
			User iUser = users.get(i);
			
			SFSArray sfsUserArray = new SFSArray();
			for(int j = 0; j < users.size(); j++){			
				User jUser = users.get(j);				
				Player iPlayer = mahjong.getPlayerById(jUser.getId());
				
				Response.Builder oUser = new Response.Builder();
				oUser.name(jUser.getName())
					.id(jUser.getId())
					.position(iPlayer.getPlayerPosition())
					.isItMe(iUser.getId() == jUser.getId() ? true : false);				
				
				sfsUserArray.addSFSObject(oUser.build().getSFSObject());			
			}
			
			Response.Builder response = new Response.Builder();
			response.users(sfsUserArray);
			send(GameActionType.updateRoom.toString(), response.build().getSFSObject(), iUser);
		}
		
		ext.addAction(user, GameActionType.updateRoom.toString());
	}

}
